﻿package com.web;


import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.dao.UserDao;
import com.entity.User;

public class LoginServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		request.getRequestDispatcher("/WEB-INF/pms/index.jsp").forward(request, response);
		
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	
		String name=request.getParameter("username");
		
		String password=request.getParameter("password");
		
		if(name==null||"".equals(name)||password==null||"".equals(password)){
			
			response.sendRedirect("login.jspx?code=10002");
			return;
		}
		
		UserDao dao=new UserDao();
		User user = dao.findByName(name);
		if(user != null && user.getPassword().equals(password)) {
			HttpSession session = request.getSession();
			session.setAttribute("user", user);
			
			String where = (String) session.getAttribute("where");
			if(where != null) {
				session.removeAttribute("where");
				response.sendRedirect(where);
				
			} else {
				/*if(user.getKind().equals("admin")){
					response.sendRedirect("main.jspx");
				}else if(user.getKind().equals("manager")){
					
					response.sendRedirect("main.jspxm=manager");
				}else if(user.getKind().equals("member")){
					
					response.sendRedirect("main.jspx?m=member");
				}else{
					response.sendError(404);
				}*/
				
				request.getRequestDispatcher("main.jsp").forward(request, response);
				/*response.sendRedirect("main.jspx");*/
			}
			
		} else {
			response.sendRedirect("login.jspx?code=10001");
		}
	
	}

}